package Week2.J0422;

public class 岛屿数量 {
//    public static void main(String[] args) {
//
//        char[][] grid = {
////                {'1', '1', '0', '0', '0'},
////                {'0', '1', '0', '1', '1'},
////                {'0', '0', '0', '1', '1'},
////                {'0', '0', '0', '0', '0'},
////                {'0', '0', '1', '1', '1'}
//                {'0', '1', '0', '1', '1'},
//                {'0', '0', '0', '1', '1'},
//        };
//
//        System.out.println(solve(grid));
//    }

    static int[] dx = {0, 0, 1, -1};
    static int[] dy = {1, -1, 0, 0};
    static int sum = 0;
    static int count = 0;

    static boolean[][] isVis;
    public static int solve (char[][] chgrid) {
        int m = chgrid.length;
        int n = chgrid[0].length;

        isVis = new boolean[m][n];

        int[][] grid = new int[m][n];

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                grid[i][j] = Character.getNumericValue(chgrid[i][j]);
            }
        }

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1 && !isVis[i][j]) {
                    searchLand(grid, i, j);
                }
                if (count >= 2) {
                    sum++;
                }
                count = 0;
            }
        }
        return sum;
    }

    private static void searchLand(int[][] grid, int i, int j) {
        count++;
        isVis[i][j] = true;
        for (int k = 0; k < 4; k++) {
            int x = i + dx[k];
            int y = j + dy[k];
            if (x >= 0 && x < grid.length && y >= 0 && y < grid[0].length && !isVis[x][y]) {
                if (grid[x][y] == 1) {
                    searchLand(grid, x, y);
                }
            }
        }
    }
}